<template>
  <a-form
    ref="loginForm"
    :model="userInfo"
    class="login-form"
    layout="vertical"
    @submit="handleSubmit"
  >
    <a-form-item
      field="username"
      :rules="[{ required: true, message: '请输入手机号' }]"
      :validate-trigger="['change', 'blur']"
      hide-label
    >
      <a-input v-model="userInfo.mobile" placeholder="请输入手机号">
        <template #prefix>
          <icon-user />
        </template>
      </a-input>
    </a-form-item>
    <a-form-item
      field="code"
      :rules="[{ required: true, message: '请输入验证码' }]"
      :validate-trigger="['change', 'blur']"
      hide-label
    >
      <a-input v-model="userInfo.code" placeholder="请输入验证码" allow-clear>
        <template #prefix>
          <icon-lock />
        </template>
      </a-input>
    </a-form-item>
    <a-space :size="16" direction="vertical">
      <a-button type="primary" html-type="submit" long :loading="loading">
        {{ $t('login.form.login') }}
      </a-button>
      <a-button type="text" long class="login-form-register-btn">
        {{ $t('login.form.register') }}
      </a-button>
    </a-space>
  </a-form>
</template>

<script setup lang="ts">
  import useLoading from '@/hooks/loading';
  import { useUserStore } from '@/store';
  import { useStorage } from '@vueuse/core';
  import { reactive, ref } from 'vue';
  import { ValidatedError } from '@arco-design/web-vue/es/form/interface';
  import type { LoginData } from '@/api/user';
  import { Message } from '@arco-design/web-vue';
  import { useRouter } from 'vue-router';
  import { useI18n } from 'vue-i18n';

  const router = useRouter();
  const { t } = useI18n();
  const { loading, setLoading } = useLoading();
  const userStore = useUserStore();
  const errorMessage = ref('');
  const loginConfig = useStorage('login-config-mobile', {
    rememberPassword: true,
    mobile: 'admin', // 演示默认值
    code: '1234', // demo default value
  });
  const userInfo = reactive({
    mobile: loginConfig.value.mobile,
    code: loginConfig.value.code,
  });

  const handleSubmit = async ({
    errors,
    values,
  }: {
    errors: Record<string, ValidatedError> | undefined;
    values: Record<string, any>;
  }) => {
    if (loading.value) return;
    if (!errors) {
      setLoading(true);
      try {
        await userStore.login(values as LoginData);
        const { redirect, ...othersQuery } = router.currentRoute.value.query;
        router.push({
          name: (redirect as string) || 'Workplace',
          query: {
            ...othersQuery,
          },
        });
        Message.success(t('login.form.login.success'));
      } catch (err) {
        errorMessage.value = (err as Error).message;
      } finally {
        setLoading(false);
      }
    }
  };
</script>

<style scoped lang="less"></style>
